package usr

import (
	"fmt"
	"sync"
	"xian-server/lib/database"
	"xian-server/lib/utils/transf"
)

type BaseUsrDao struct {
	Model *BaseUsr
}

var (
	instanceBaseUsrDao *BaseUsrDao //单例的对象
	onceBaseUsrDao     sync.Once
)

func NewBaseUsrDao() *BaseUsrDao {
	onceBaseUsrDao.Do(func() {
		instanceBaseUsrDao = &BaseUsrDao{Model: NewBaseUsrModel()}
	})
	return instanceBaseUsrDao
}

// 创建
func (d *BaseUsrDao) CreateBaseUsr(model *BaseUsr) (string, error) {
	fields, vals := transf.GetStructKV(model, []string{"id"}, true)
	id, err := database.NewDAO(d.Model).Insert(fields, vals)
	if err != nil {
		return "", err
	}

	fmt.Printf("result: %v\n", id)
	return id, nil
}

// 根据 id 删除 base_usr
func (d *BaseUsrDao) DeleteBaseUsrById(id *BaseUsrId) error {
	_, err := database.NewDAO(d.Model).Delete(string(*id))
	if err != nil {
		return err
	}
	return nil
}

// 根据 id 修改 base_usr
func (d *BaseUsrDao) UpdateBaseUsrById(id *BaseUsrId, model *BaseUsr) error {
	fields, vals := transf.GetStructKV(model, []string{"id"}, true)
	_, err := database.NewDAO(d.Model).Update(fields, vals, "")
	if err != nil {
		return err
	}
	return nil
}

// 查询全部 base_usr
func (d *BaseUsrDao) FindAllBaseUsr() (*[]BaseUsr, error) {
	list := d.Model.NewSplice()
	if err := database.NewDAO(d.Model).Lists(list, ""); err != nil {
		return list, err
	}
	return list, nil
}
